﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Data;
using System.Data.SqlClient;

namespace Webdisk
{
    public class DBHelper
    {
        //数据库连接字符串
        //public static string ConnString = "server=.;database=Webdisk;integrated security=true";
        public static string ConnString = "server = 134.175.15.205;database = Webdisk;uid=sa;pwd=WHXL_whxl_1024";


        //数据库连接对象
        public static SqlConnection Conn = null;

        //初始化数据库连接
        public static void InitConnection()
        {
            //如果连接对象不存在，则创建连接
            if (Conn == null)
                Conn = new SqlConnection(ConnString);
            //如果连接对象关闭，则打开连接
            if (Conn.State == ConnectionState.Closed)
                Conn.Open();
            //如果连接中断，则重新连接
            if (Conn.State == ConnectionState.Broken)
            {
                Conn.Close();
                Conn.Open();
            }
        }

        //增删改
        public static bool ExecuteNonQuery(string sqlStr)
        {
            string a = sqlStr;
            InitConnection();
            SqlCommand cmd = new SqlCommand(sqlStr, Conn);
            int result = cmd.ExecuteNonQuery();
            Conn.Close();
            return result > 0;
        }

        //查询，获取DataTable
        public static DataTable GetDataTable(string sqlStr)
        {
            InitConnection();
            DataTable ds = new DataTable();
            SqlDataAdapter dap = new SqlDataAdapter(sqlStr, Conn);
            dap.Fill(ds);
            Conn.Close();
            return ds;

        }
		public static DataSet GetDataSet(string strSql)
		{
			DataSet ds = new DataSet();
			InitConnection();
			SqlDataAdapter dap = new SqlDataAdapter(strSql, Conn);
			dap.Fill(ds);
			Conn.Close();
			return ds;
		}

		//查询，获取DataReader
		public static SqlDataReader GetDataReader(string sqlStr)
        {
            InitConnection();
            SqlCommand cmd = new SqlCommand(sqlStr, Conn);
            return cmd.ExecuteReader(CommandBehavior.CloseConnection);
        }

        //执行聚合函数
        public static object ExecusteScalar(string sqlStr)
        {
            InitConnection();
            SqlCommand cmd = new SqlCommand(sqlStr, Conn);
            object result = cmd.ExecuteScalar();
            Conn.Close();
            return result;
        }
    }
}
